package edu.nf.llmtest.service.impl;

import edu.nf.llmtest.service.TrafficService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ Author bin
 * @ Create  2025/11/3 下午7:24
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class TrafficServiceImpl implements TrafficService {
    String apiKey = "3b6a22a5f50fe06b37d5131f7d91c3dc";
    String apiUrl = "https://apis.juhe.cn/fapigw/train/query";
    @Override
    public StringBuffer getTrafficInfo(String departure_station , String arrival_station ,
                                       String date, String filter,
                                       String enable_booking,String departure_time_range) throws Exception{
        HashMap<String, String> map = new HashMap<>();
        map.put("key", apiKey); //apikey
        map.put("search_type", "通过站点名称"); //查询方式
        map.put("departure_station", departure_station); // 出发站
        map.put("arrival_station", arrival_station); // 到达站
        map.put("date", date); // 查询时间
        map.put("filter", filter); // 车次筛选条件，默认所有。如：G
        map.put("enable_booking", enable_booking); // 是否可预订
        map.put("departure_time_range", departure_time_range); // 出发时间范围
        URL url = new URL(String.format("%s?%s", apiUrl, params(map)));
        BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        log.info("火车班次查询结果：{}", response);
        return response;
    }

    public static String params(Map<String, String> map) {
        return map.entrySet().stream()
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return entry.getKey() + "=" + entry.getValue();
                    }
                })
                .collect(Collectors.joining("&"));
    }

    public static Map<String,Object> functionSchema() {
        return  Map.of(
                "name", "query_train_schedule",
                "description", "根据出发地、目的地、出发日期查询火车班次",
                "parameters", Map.of(
                        "type", "object",
                        "properties", Map.of(
                                "departure_station", Map.of("type", "string", "description", "出发站。如：北京"),
                                "arrival_station", Map.of("type", "string", "description", "到达站。如：上海"),
                                "date", Map.of("type", "string", "description", "出发日期。格式：YYYY-MM-DD，如：2025-11-07。仅允许15天内的日期"),
                                "filter", Map.of("type", "string", "description", "车次筛选条件，默认为空字符串表示所有。如：G表示高铁，D表示动车"),
                                "enable_booking", Map.of("type", "string", "description", "是否可预定班次，默认：1。1-仅返回可预定的班次，2-所有"),
                                "departure_time_range", Map.of("type", "string", "description", "出发时间选择，默认为空字符串。如：早晨-[06:00-12:00)")
                        ),
                        "required", List.of("departure_station", "arrival_station", "date")
                )
        );
    }
}
